package com.mzj.saas.rent;


import cn.hutool.core.date.DateUtil;
import com.haixiaoke.saas.repository.core.AjaxResult;
import com.haixiaoke.saas.repository.core.BaseController;
import com.haixiaoke.saas.repository.core.HttpStatus;
import com.haixiaoke.saas.repository.core.page.TableDataInfo;
import com.haixiaoke.saas.repository.pojo.UserFloatingPopulationRecord;
import com.haixiaoke.saas.repository.service.IUserFloatingPopulationRecordService;
import com.haixiaoke.saas.repository.vo.UserFloatingPopulationRecordVo;
import com.mzj.saas.annotation.CheckAuth;
import com.mzj.saas.commons.DownloadUtil;
import com.mzj.saas.commons.Export2Util;
import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.mservice.community.service.AppCommunityService;
import com.mzj.saas.mservice.eligible.entity.DepartmentEnterpriseTagRef;
import com.mzj.saas.mservice.eligible.entity.DepartmentHierarchy;
import com.mzj.saas.mservice.eligible.repository.DepartmentEnterpriseTagRefRepository;
import com.mzj.saas.mservice.eligible.repository.DepartmentHierarchyRepository;
import com.mzj.saas.util.LoginUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 流动用户记录Controller
 *
 * @author qixi
 * @date 2023-07-25
 */
@RestController
@RequestMapping("/floatingPopulation")
@Slf4j
public class UserFloatingPopulationRecordController extends BaseController {
    @Autowired
    private IUserFloatingPopulationRecordService userFloatingPopulationRecordService;
    @Autowired
    private DepartmentEnterpriseTagRefRepository departmentEnterpriseTagRefRepository;
    @Autowired
    private DepartmentHierarchyRepository departmentHierarchyRepository;
    @Autowired
    private AppCommunityService appCommunityService;
    @Autowired
    private LoginUserUtil loginUserUtil;
    @Value("${contract.tmp.dir}")
    private String contractTmpDir;

    /**
     * 查询流动用户记录列表
     */
    @GetMapping("/list")
    public TableDataInfo list(UserFloatingPopulationRecord userFloatingPopulationRecord) {
        startPage();
        String token = loginUserUtil.getToken();
        //权限过滤
        List<Map<String, Object>> communityList = appCommunityService.findCommunity(token).getResultData();
        if (communityList != null && !communityList.isEmpty()) {
            List<String> communityIds = communityList.stream().map(map -> map.get("communityId")
                    .toString()).collect(Collectors.toList());
            userFloatingPopulationRecord.setCommunityIds(communityIds);
        } else {
            //如果不存在小区信息，则直接返回
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.SUCCESS);
            rspData.setMsg("查询成功");
            rspData.setRows(null);
            rspData.setTotal(0);
            return rspData;
        }
        List<UserFloatingPopulationRecordVo> list = userFloatingPopulationRecordService.selectUserFloatingPopulationRecordAndHouseInfoList(userFloatingPopulationRecord);
        return getDataTable(list);
    }


    /**
     * 获取流动用户记录详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(userFloatingPopulationRecordService.selectUserFloatingPopulationRecordById(id));
    }


    /**
     * 导出流动用户记录列表
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response, @RequestBody  UserFloatingPopulationRecordVo vo) throws Exception {
        // Long orgId = loginUserUtil.getOrgId();
        // vo.setOrgId(orgId);
        List<UserFloatingPopulationRecordVo> populationRecordVos = userFloatingPopulationRecordService.selectUserFloatingPopulationRecordAndHouseInfoListByPopulationIds(vo);

        // 表格头
        Map<String, String> map = new LinkedHashMap<>();
        map.put("小区", "eCommunityName");
        map.put("楼栋", "buildingNumName");
        map.put("单元", "unitName");
        map.put("房号", "roomNumber");
        map.put("姓名", "userName");
        map.put("联系方式", "userPhone");
        map.put("入住时间", "createTimeFormat");
        map.put("迁出时间", "quitTimeFormat");

        String fileName = "流动人口记录表_" + System.currentTimeMillis();
        populationRecordVos.forEach(m -> {
            m.setCreateTimeFormat(DateUtil.format(m.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
            m.setQuitTimeFormat(DateUtil.format(m.getQuitTime(), "yyyy-MM-dd HH:mm:ss"));
        });
        Workbook workbook = new Export2Util().getExcelByTemplate(populationRecordVos, map, "importAndExport", "流动人口导出模板.xlsx", 2);

        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
      /*  response.setContentType("application/octet-stream;charset=utf-8");
        ServletOutputStream outputstream = response.getOutputStream();//取得输出流

        // 生成文件
        File file = new File("流动人口记录表" + ".xlsx");
        OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            workbook.write(out);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


        File[] srcFiles = {file};
        File zipFile = new File(contractTmpDir + "ZipFile.zip");
        CommunityService.zipFiles(srcFiles, zipFile);
        byte[] zip = CommunityService.File2byte(zipFile);
        outputstream.write(zip);
        outputstream.flush();//刷数据
        // 关闭
        workbook.close();*/

        DownloadUtil downloadUtil = new DownloadUtil();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        workbook.write(bos);
        downloadUtil.download(bos,response, URLEncoder.encode(fileName + ".xlsx", "utf-8"));
        workbook.close();
    }

    /**
     * 新增流动用户记录
     */
    @PostMapping
    public AjaxResult add(@RequestBody UserFloatingPopulationRecord userFloatingPopulationRecord) {
        return toAjax(userFloatingPopulationRecordService.insertUserFloatingPopulationRecord(userFloatingPopulationRecord));
    }

    /**
     * 修改流动用户记录
     */
    @PutMapping
    public AjaxResult edit(@RequestBody UserFloatingPopulationRecord userFloatingPopulationRecord) {
        return toAjax(userFloatingPopulationRecordService.updateUserFloatingPopulationRecord(userFloatingPopulationRecord));
    }

    /**
     * 删除流动用户记录
     */
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(userFloatingPopulationRecordService.deleteUserFloatingPopulationRecordByIds(ids));
    }

    /**
     * 本日人员数据统计
     */
    @GetMapping(value = "/todayPersonnel")
    @CheckAuth
    public ResultBean<UserFloatingPopulationRecord> todayPersonnel(@RequestParam(required = false) String residenceCommunityId) {
        String token = loginUserUtil.getToken();
        Long orgId = loginUserUtil.getOrgId();
        //权限过滤
        List<String> communityIds = null;
        List<Map<String, Object>> communityList = appCommunityService.findCommunity(token).getResultData();
        if (communityList != null && !communityList.isEmpty()) {
            communityIds = communityList.stream().map(map -> map.get("communityId")
                    .toString()).collect(Collectors.toList());
        }
        return ResultBean.successfulResult(userFloatingPopulationRecordService.todayPersonnel(orgId,residenceCommunityId,communityIds));
    }

    /**
     * 获取当前月有多少周
     */
    @GetMapping(value = "/weekNumber")
    @CheckAuth
    public ResultBean <List<Map<String, Object>>> getWeekNumber() {
        return ResultBean.successfulResult(userFloatingPopulationRecordService.getWeekNumber());
    }

    /**
     * 周人员类型数据统计
     * @param residenceCommunityId 小区id
     * @param weeklyNumber 周数
     * @return
     */
    @GetMapping(value = "/weeklyPersonnel")
    @CheckAuth
    public ResultBean<UserFloatingPopulationRecord> weeklyPersonnel(@RequestParam(required = false) String residenceCommunityId,
                                                                        @RequestParam(required = false) Integer weeklyNumber) {
        String token = loginUserUtil.getToken();
        Long orgId = loginUserUtil.getOrgId();
        //权限过滤
        List<String> communityIds = null;
        List<Map<String, Object>> communityList = appCommunityService.findCommunity(token).getResultData();
        if (communityList != null && !communityList.isEmpty()) {
            communityIds = communityList.stream().map(map -> map.get("communityId")
                    .toString()).collect(Collectors.toList());
        }
        return ResultBean.successfulResult(userFloatingPopulationRecordService.weeklyPersonnel(orgId,residenceCommunityId,weeklyNumber,communityIds));
    }

    /**
     * 月度人员数据统计
     * @param residenceCommunityId 小区id
     * @param month 月份
     * @return
     */
    @GetMapping(value = "/monthPersonnel")
    @CheckAuth
    public ResultBean<UserFloatingPopulationRecord> monthPersonnel(@RequestParam(required = false) String residenceCommunityId,
                                                                    @RequestParam(required = false) Integer month) {
        String token = loginUserUtil.getToken();
        Long orgId = loginUserUtil.getOrgId();
        //权限过滤
        List<String> communityIds = null;
        List<Map<String, Object>> communityList = appCommunityService.findCommunity(token).getResultData();
        if (communityList != null && !communityList.isEmpty()) {
            communityIds = communityList.stream().map(map -> map.get("communityId")
                    .toString()).collect(Collectors.toList());
        }
        return ResultBean.successfulResult(userFloatingPopulationRecordService.monthPersonnel(orgId,residenceCommunityId,month,communityIds));
    }

    /**
     * 季度人员数据统计
     * @param residenceCommunityId 小区id
     * @param quarter 季度
     * @return
     */
    @GetMapping(value = "/quarterPersonnel")
    @CheckAuth
    public ResultBean<UserFloatingPopulationRecord> quarterPersonnel(@RequestParam(required = false) String residenceCommunityId,
                                                                   @RequestParam(required = false) Integer quarter) {
        String token = loginUserUtil.getToken();
        Long orgId = loginUserUtil.getOrgId();
        //权限过滤
        List<String> communityIds = null;
        List<Map<String, Object>> communityList = appCommunityService.findCommunity(token).getResultData();
        if (communityList != null && !communityList.isEmpty()) {
            communityIds = communityList.stream().map(map -> map.get("communityId")
                    .toString()).collect(Collectors.toList());
        }
        return ResultBean.successfulResult(userFloatingPopulationRecordService.quarterPersonnel(orgId,residenceCommunityId,quarter,communityIds));
    }

    /**
     * 年度人员数据统计
     * @param residenceCommunityId 小区id
     * @param year 年度
     * @return
     */
    @GetMapping(value = "/yearPersonnel")
    @CheckAuth
    public ResultBean<UserFloatingPopulationRecord> yearPersonnel(@RequestParam(required = false) String residenceCommunityId,
                                                                     @RequestParam(required = false) Integer year) {
        String token = loginUserUtil.getToken();
        Long orgId = loginUserUtil.getOrgId();

        //权限过滤
        List<String> communityIds = null;
        List<Map<String, Object>> communityList = appCommunityService.findCommunity(token).getResultData();
        if (!communityList.isEmpty()) {
            communityIds = communityList.stream().map(map -> map.get("communityId")
                    .toString()).collect(Collectors.toList());
        }
        return ResultBean.successfulResult(userFloatingPopulationRecordService.yearPersonnel(orgId,residenceCommunityId,year,communityIds));
    }

    /**
     * 总人员数据统计
     */
    @GetMapping(value = "/personnelInfo")
    @CheckAuth
    public ResultBean<UserFloatingPopulationRecord> personnelInfo(@RequestParam(required = false) String residenceCommunityId) {
        String token = loginUserUtil.getToken();
        Long orgId = loginUserUtil.getOrgId();
        //DepartmentHierarchy hierarchy = departmentHierarchyRepository.findByOrgIdAndStatus(orgId, 1);
        //if (hierarchy == null) {
        //    return ResultBean.failedResultWithMsg("用户所属机构未设置层级架构");
        //}
        //Map<String, Object> hierarchyMap = getHierarchy(hierarchy);
        //Long areaId = (Long) hierarchyMap.get("areaId");
        //String areaTag = (String) hierarchyMap.get("areaTag");
        //权限过滤
        List<String> communityIds = null;
        List<Map<String, Object>> communityList = appCommunityService.findCommunity(token).getResultData();
        if (!communityList.isEmpty()) {
            communityIds = communityList.stream().map(map -> map.get("communityId")
                    .toString()).collect(Collectors.toList());
        }
        return ResultBean.successfulResult(userFloatingPopulationRecordService.personnelInfo(orgId,residenceCommunityId,communityIds));
    }

    public Map<String,Object> getHierarchy(DepartmentHierarchy hierarchy) {
        Map<String, Object> map = new HashMap<>();
        Long id = hierarchy.getId();
        List<DepartmentEnterpriseTagRef> refs = departmentEnterpriseTagRefRepository.findByDepRefId(id);
        List<Long> enterpriseTagIds = refs.stream().map(DepartmentEnterpriseTagRef::getTagId).distinct().collect(Collectors.toList());//用户企业标签

        //1、政府机构，根据区域标签所对应区域id查
        Long areaTagId = hierarchy.getTagId();//区域标签
        Long areaId = null;
        if (enterpriseTagIds.contains(3L)) {
            areaId = hierarchy.getAreaId();//区域id
        }
        String areaTag = "h.province_id";
        if (areaTagId == 1) {
            areaTag = "h.province_id";
        } else if (areaTagId == 2) {
            areaTag = "h.city_id";
        } else if (areaTagId == 3) {
            areaTag = "h.district_id";
        } else if (areaTagId == 4) {
            areaTag = "h.street_id";
        } else if (areaTagId == 5) {
            areaTag = "h.community_id";
        }
        map.put("areaId",areaId);
        map.put("areaTag",areaTag);
        return map;
    }
}
